package com.gz.mylife.im;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.im.MessageChannel.Meta;
import com.gz.mylife.util.ImageUtils;
import com.gz.mylife.widget.LoadingCover;
import com.gz.mylife.widget.OfflineDialog;
import com.gz.mylife.widget.PullToRefreshListView;
import com.gz.mylife.widget.LoadingCover.OnLoadingCoverRefreshListener;
import com.gz.mylife.widget.PullToRefreshListView.OnLastItemVisibleListener;
import com.gz.mylife.widget.PullToRefreshListView.OnRefreshListener;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.zl.smartmall.library.account.IAuth;
import com.zl.smartmall.library.util.Constants;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.PreferenceModel;
import com.zl.smartmall.library.util.SingtonAsyncHttpClient;
import com.zl.smartmall.library.util.Tools;

public class FragmentSession extends Fragment implements OnClickListener,Observer, OnLastItemVisibleListener, OnRefreshListener, OnLoadingCoverRefreshListener {

	private final static String TAG = "DT_Session";

	private final static String KEY_FIRST_GET = "key.sms.first.get";
	private final static int MSG_FIRST_GET = 1;
	private final static int MSG_GET_UNRECEIVED = 2;
	private final static int MSG_HID_PMID = 3;
	private final static int MSG_NO_MORE_DATA = 4;
	
	private Session mActivity;
	private Context mContext;

	private OfflineDialog mOfflineDialog;
	//private FooterView mFooterView;
	private LoadingCover mLoadingCover;
	private PullToRefreshListView mListView;
	private SessionAdapter mAdapter;

	private DisplayImageOptions mOptions;
	private List<SessionBean> mDataList;
	
	private boolean isLeisure = true;
	private Result mResult;
	
	private MyHandler mHandler;
	
	private boolean isFirst;
	private View mFootview;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		mActivity = (Session) getActivity();
		mContext = mActivity.getApplicationContext();
		MessageChannel.get().register(MessageChannel.SESSION,this);
		mHandler = new MyHandler(this);

		View view = inflater.inflate(R.layout.fragment_session, container, false);
		
		mFootview = inflater.inflate(R.layout.session_footerview, null);
		TextView mNoData = (TextView) mFootview.findViewById(R.id.tv_nodata);
		RelativeLayout.LayoutParams noDataParams = (LayoutParams) mNoData.getLayoutParams();
		WindowManager wm = getActivity().getWindowManager();
		noDataParams.height = wm.getDefaultDisplay().getHeight() - Tools.dip2px(mContext, 80);
		mOfflineDialog = (OfflineDialog) inflater.inflate(R.layout.offline_dialog, null);
		mLoadingCover = (LoadingCover) view.findViewById(R.id.layout_loading_cover);
		mListView = (PullToRefreshListView) view.findViewById(R.id.listView);
		mListView.setOnLastItemVisibleListener(this);
//		mListView.setOnRefreshListener(this);
		
		mDataList = new ArrayList<SessionBean>();
		mAdapter = new SessionAdapter(mActivity,mListView, mDataList,mHandler);
		CrashHandler.d(TAG, "mDataList:"+mDataList.size());
		mListView.setAdapter(mAdapter);
		
		mLoadingCover.setOnLoadingCoverRefreshListener(this);
		
		mResult = new Result(mActivity);
		mResult.setListView(mListView);
		mResult.setLoadingEmpty(mLoadingCover);
		
		isFirst = FirstEnterAppTagDao.isFirst(mContext);
		return view;
	}
	
	@Override
	public void onRefresh() {
		RequestParams params = new RequestParams();
		mResult.pull(params);
		params.put("limit", "99999");
		SingtonAsyncHttpClient.getInstance().setCookieStore(IAuth.getInstance().loadCookieStore());
		SingtonAsyncHttpClient.getInstance().get(Constants.URL_RECEIVE_SESSION, params, new GetAllSessionReponse());
	}
	
	@Override
	public void onResume() {
		super.onResume();
		
		List<SessionBean> mDataListTemp = SessionDao.findSessionFirstByLimit(mContext, 0);
		if(mDataListTemp.size()<=0||isFirst){
			mLoadingCover.setVisibility(View.VISIBLE);
//			mDataList = new ArrayList<SessionBean>();
			// TODO
			RequestParams params = new RequestParams();
			mResult.first(params);
			params.put("limit", "99999");
			SingtonAsyncHttpClient.getInstance().setCookieStore(IAuth.getInstance().loadCookieStore());
			SingtonAsyncHttpClient.getInstance().get(Constants.URL_RECEIVE_SESSION, params, new GetAllSessionReponse());
		}else{
			mDataList.clear();
			mDataList.addAll(mDataListTemp);
			sortSession(mDataList);
			mLoadingCover.setVisibility(View.GONE);
		}
		
		
		mAdapter.notifyDataSetChanged();
		
//		PreferenceModel.putInt(PreferenceModel.unread_count_sms, 0);
	}
	private void sortSession(List<SessionBean> mDataList2) {
		List<SessionBean> lists = new ArrayList<SessionBean>();
		for(int i = 0;i<mDataList2.size();i++){
			SessionBean bean = mDataList2.get(i);
			if(bean.getPmid()>0){
				lists.add(bean);
			}
		}
		for(int i = 0;i<mDataList2.size();i++){
			SessionBean bean = mDataList2.get(i);
			if(bean.getPmid()<0){
				lists.add(bean);
			}
		}
		mDataList = lists;
	}
	public static class MyHandler extends Handler{
		private FragmentSession mOuter;
		public MyHandler(FragmentSession outer){
			mOuter = outer;
		}
		public void release(){
			new WeakReference<FragmentSession>(mOuter);
		}
		
		@Override
		public void handleMessage(Message msg) {
			if(mOuter == null){
				return;
			}
			switch (msg.what) {
			case MSG_FIRST_GET:
				// 清除数据，不包含回复和关注
				for(int i= mOuter.mDataList.size()-1;i >= 0;i--){
					SessionBean tempItem = mOuter.mDataList.get(i);
					if(tempItem.getPmid() > 0){
						mOuter.mDataList.remove(i);
					}
				}
				List<SessionBean> data = (List<SessionBean>)msg.obj;
//				if(data.size() > SessionDao.LIMIT){
//					mOuter.mDataList.addAll(0,data.subList(0, SessionDao.LIMIT));
//				} else {
//					mOuter.mDataList.addAll(0,data);
//				}
				if(data.size() == 0){
					if(mOuter.mListView.getFooterViewsCount()==0){
						mOuter.mListView.addFooterView(mOuter.mFootview);
					}
				}else{
					if(mOuter.mListView.getFooterViewsCount()==0){
						mOuter.mListView.removeFooterView(mOuter.mFootview);
					}
				}
				mOuter.mDataList.addAll(0,data);
				mOuter.sortSession(mOuter.mDataList);
				mOuter.mLoadingCover.setVisibility(View.GONE);
				mOuter.mAdapter.notifyDataSetChanged();
				break;
			case MSG_GET_UNRECEIVED:
				List<SessionBean> data2 = (List<SessionBean>)msg.obj;
				for(int i= mOuter.mDataList.size()-1;i >= 0;i--){
					SessionBean tempItem = mOuter.mDataList.get(i);
					if(tempItem.getPmid() > 0){
						mOuter.mDataList.remove(i);
					}
				}
//				if(data2.size() > SessionDao.LIMIT){
//					mOuter.mDataList.addAll(data2.subList(0, SessionDao.LIMIT));
//				} else {
//					mOuter.mDataList.addAll(data2);
//				}
				mOuter.mDataList.addAll(0,data2);
				mOuter.sortSession(mOuter.mDataList);
				mOuter.mLoadingCover.setVisibility(View.GONE);
				mOuter.mAdapter.notifyDataSetChanged();
				break;
			case MSG_HID_PMID:
//				SessionBean bean = (SessionBean)msg.obj;
//				mOuter.mDataList.remove(bean);
//				mOuter.sortSession(mOuter.mDataList);
//				mOuter.mAdapter.notifyDataSetChanged();
				if(mOuter.mDataList.size() == 0){
					if(mOuter.mListView.getFooterViewsCount()==0){
						mOuter.mListView.addFooterView(mOuter.mFootview);
					}
				}else{
					if(mOuter.mListView.getFooterViewsCount()>0){
						mOuter.mListView.removeFooterView(mOuter.mFootview);
					}
				}
				break;
			case MSG_NO_MORE_DATA:
				mOuter.mLoadingCover.setVisibility(View.GONE);
				if(mOuter.mDataList.size() == 0){
					if(mOuter.mListView.getFooterViewsCount()==0){
						mOuter.mListView.addFooterView(mOuter.mFootview);
					}
				}else{
					if(mOuter.mListView.getFooterViewsCount()>0){
						mOuter.mListView.removeFooterView(mOuter.mFootview);
					}
				}
				break;

			default:
				break;
			}
		}
	}
	@Override
	public void onLastItemVisible() {
		if(mDataList.size() == 0){
			return;
		}
		long dateline = mDataList.get(mDataList.size() - 1).getDateline();
		if (isLeisure && SessionDao.hasNext(mContext,dateline)) {
			isLeisure = false;
//			List<SessionBean> sessions = SessionDao.findSessionByLimit(mContext, mDataList.size());
//			mDataList.addAll(sessions);
//			mAdapter.notifyDataSetChanged();
			isLeisure = true;
		}
	}
	
	
	public Comparator<SessionBean> mComparator = new  Comparator<SessionBean>(){
		@Override
		public int compare(SessionBean arg0, SessionBean arg1) {
			if(arg0.getPmid() > arg1.getPmid()){
				return -1;
			} else if(arg0.getPmid() < arg1.getPmid()){
				return 1;
			} else {
				return 0;
			}
		}
	};
	
	public Comparator<SessionBean> mSortComparator = new  Comparator<SessionBean>(){
		@Override
		public int compare(SessionBean arg0, SessionBean arg1) {
			if(arg0.getDateline() > arg1.getDateline()){
				return -1;
			} else if(arg0.getDateline() < arg1.getDateline()){
				return 1;
			} else {
				return 0;
			}
		}
	};

	@Override
	public void onDestroy() {
		super.onDestroy();
		MessageChannel.get().unregister(MessageChannel.SESSION,this);
		ImageUtils.unbindDrawables(mListView);
		mActivity = null;
		mHandler.release();
		System.gc();
	}


	@Override
	public void onClick(View arg0) {
		if(arg0 == mLoadingCover){
			RequestParams params = new RequestParams();
			mResult.first(params);
			params.put("limit", "99999");
			SingtonAsyncHttpClient.getInstance().setCookieStore(IAuth.getInstance().loadCookieStore());
			SingtonAsyncHttpClient.getInstance().get(Constants.URL_RECEIVE_SESSION, params, new GetAllSessionReponse());
			
		} 
//		else if (arg0 == mFooterView) {
//			if(mDataList.size() > 0 && SessionDao.hasNext(mContext, mDataList.get(mDataList.size()-1).getId())) {
//				List<SessionBean> sessions = SessionDao.findSessionByLimit(mContext, mDataList.get(mDataList.size()-1).getId());
//				mDataList.addAll(sessions);
//				mAdapter.notifyDataSetChanged();
//				
//				if(!SessionDao.hasNext(mContext, mDataList.get(mDataList.size()-1).getId())){
//					mFooterView.stopLoading(Define.MSG_NO_MORE_DATA);
//					mFooterView.setOnClickListener(null);
//				}
//			}
//		}
	}
	
	class GetAllSessionReponse extends JsonHttpResponseHandler{
		private List<SessionBean> lists;
		
		@Override
		public void onStart() {
			mResult.start();
		}
		
		@Override
		protected Object parseResponse(byte[] responseBody)
				throws JSONException {
			// TODO Auto-generated method stub
			Object object = super.parseResponse(responseBody);
			if(object instanceof JSONObject){
				JSONObject response = (JSONObject) object;
				int ret = response.getInt("ret");
				if(ret == 0){
					JSONObject result = response.getJSONObject("result");
					lists = new ArrayList<SessionBean>();
					List<SessionBean> data = SessionDao.adapter(result.getJSONArray("pmid_data"));
					if(isFirst){
						for(int i = 0;i<data.size();i++){
							SessionBean bean = data.get(i);
							SessionBean nativeBean = SessionDao.getSession(mContext, bean);
							if(nativeBean != null){
								comparisonToNative(bean, nativeBean);
							}else{
								lists.add(bean);
							}
						}
						FirstEnterAppTagDao.reSet(mContext);
						isFirst = false;
					}else{
						for(int i = 0;i<data.size();i++){
							SessionBean bean = data.get(i);
							SessionBean nativeBean = SessionDao.getSession(mContext, bean);
							if(nativeBean != null){
								comparisonToNative(bean, nativeBean);
							}else{
								bean.setUnreadCount(bean.getMsgid());
								int unReadCount = PreferenceModel.getInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, 0);
								PreferenceModel.putInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, unReadCount+bean.getMsgid());
								lists.add(bean);
							}
						}
					}
					if(mResult.getReqtype() == Result.FIRST || mResult.getReqtype() == Result.PULL){
						SessionDao.save(mContext, data);
					}
					
				}else if(ret == 4){
					if(isFirst){
						FirstEnterAppTagDao.reSet(mContext);
						isFirst = false;
					}
				}
			} 
			return object;
		}

		public void comparisonToNative(SessionBean bean, SessionBean nativeBean) {
			if(nativeBean.getShowStatus() == 1){//隐藏
				int unReceived = bean.getMsgid() - nativeBean.getMsgid();
				if(unReceived > 0){
					bean.setUnreadCount(unReceived);
					int unReadCount = PreferenceModel.getInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, 0);
					PreferenceModel.putInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, unReadCount+unReceived);
					bean.setShowStatus(0);
					lists.add(bean);
				}else{
					bean.setShowStatus(1);
				}
			}else{
				int unReceived = bean.getMsgid() - nativeBean.getMsgid();
				if(unReceived > 0){
					bean.setUnreadCount(unReceived + nativeBean.getUnreadCount());
					int unReadCount = PreferenceModel.getInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, 0);
					PreferenceModel.putInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, unReadCount+unReceived);
				}else{
					bean.setUnreadCount(nativeBean.getUnreadCount());
				}
				lists.add(bean);
			}
		}
		
		@Override
		public void onFailure(int statusCode, Header[] headers,
				Throwable throwable, JSONObject errorResponse) {
			CrashHandler.e(throwable);
		}
		
		@Override
		public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
			
			mResult.parseResult(response);
			if(mResult.ret == 0){
//				PreferenceModel.putBoolean(KEY_FIRST_GET, false);
//				mAdapter.notifyDataSetChanged();
				Message msg = mHandler.obtainMessage(MSG_FIRST_GET, lists);
				mHandler.sendMessage(msg);
			}else if(mResult.ret == 4){
				mHandler.sendEmptyMessage(MSG_NO_MORE_DATA);
			}
		}
		
		@Override
		public void onFinish() {
			mResult.finish();
		}
		
	}

	@Override
	public void update(Observable observable, Object data) {
		Meta meta = (Meta) data;
		if(meta.msgType == MessageChannel.SESSION){
			if(isTopActivity(Session.class, getActivity())){
				SessionBean bean = (SessionBean) meta.data;
				int count = mDataList.size();
				for(int i=count-1;i>=0;i--){
					if(mDataList.get(i).equals(bean)){
						mDataList.remove(i);
						break;
					}
				}
				if(bean.getPmid() == SessionBean.PMID_COMMENT){
					int index = 0;
					for(int i = 0;i<mDataList.size();i++){
						if(mDataList.get(i).getPmid() == SessionBean.PMID_COMMENT){
							index = i;
							break;
						}
					}
					if(index>0){
						mDataList.add(index,bean);
					}else{
						mDataList.add(bean);
					}
				}else{
					mDataList.add(0, bean);
				}
//				mAdapter.updateView(0);
//				if(mDataList.size()==1){
					mAdapter = new SessionAdapter(mActivity,mListView, mDataList,mHandler);
					CrashHandler.d(TAG, "mDataList:"+mDataList.size());
					mListView.setAdapter(mAdapter);
//				}
				mAdapter.notifyDataSetChanged();
				if(mDataList.size()==1){
					if(mListView.getFooterViewsCount()>0){
						mListView.removeFooterView(mFootview);
					}
				}
			}
		}
	}

	@Override
	public void onLoadingCoverRefresh() {
		// TODO Auto-generated method stub
		
	}
	public static <T>boolean isTopActivity(Class<T> activity,Context context) {
		ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
		if (tasksInfo.size() > 0) {
			if(activity.getName().equals(tasksInfo.get(0).topActivity.getClassName())){
				return true;
			}
		}
		return false;
	}
	
}
